package com.greatchn.authorization_server.web.srv;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.greatchn.authorization_server.constant.Constant;
import com.greatchn.authorization_server.util.RedisClient;
import com.greatchn.authorization_server.util.ServiceAssert;
import com.greatchn.authorization_server.web.po.OauthUserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @LoginSrv: login srv
 * @author: ZBoHang
 * @time: 2023/3/1 13:20
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class LoginSrv {

    @Resource
    private OauthUserInfoSrv oauthUserInfoSrv;
    @Autowired
    private RedisClient redisClient;

    /**
     * login
     */
    public String login(String userName, String password) {

        OauthUserInfo oauthUserInfo = this.oauthUserInfoSrv.getByUserName(userName);
        ServiceAssert.notNull(oauthUserInfo, "用户不存在!");

        ServiceAssert.isTrue(StrUtil.equals(password, oauthUserInfo.getPassword()), "密码错误!");

        String token = IdUtil.fastSimpleUUID();

        this.redisClient.set(token, JSONUtil.toJsonStr(oauthUserInfo), Constant.TOKEN_EXPIRES);

        return token;
    }
}
